//Examples/reed_sol_crs_04.cpp

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jerasure.h"
#include "reed_sol.h"

#define talloc(type, num) (type *) malloc(sizeof(type)*(num))

void usage(char *s)
{
	fprintf(stderr, "usage: reed_sol_crs_04 n w - Prints the number of ones in the bitmatrix representation of n in GF(2^w).\n");
	fprintf(stderr, "       \n");
	fprintf(stderr, "       It also prints out the bit-matrix and confirms that the number of ones is correct.\n");
	fprintf(stderr, "       \n");
	fprintf(stderr, "This demonstrates: JER_Matrix::Set()\n");
	fprintf(stderr, "                   JER_Matrix::Matrix_To_Bitmatrix()\n");
	fprintf(stderr, "                   JER_Matrix::Get()\n");
	fprintf(stderr, "                   CRS_N_Ones()\n");
	fprintf(stderr, "                   JER_Matrix::Print()\n");
	if (s != NULL) fprintf(stderr, "%s\n", s);
	exit(1);
}

int main(int argc, char **argv)
{
	int n, i, no, w, j;
	JER_Matrix *jbm;
	JER_Matrix *jm;

	if (argc != 3) usage(NULL);
	if (sscanf(argv[1], "%d", &n) == 0 || n <= 0) usage((char *)"Bad n");
	if (sscanf(argv[2], "%d", &w) == 0 || w <= 0 || w > 32) usage((char *)"Bad w");
	if (w < 30 && n >= (1 << w)) usage((char *)"n is too big");

	jm = new JER_Matrix(1, 1, w);
	jm->Set(0,0,n);

	jbm = jm->Matrix_To_Bitmatrix();

	no = 0;
	for (i = 0; i < w; i++) { 
		for (j = 0; j < w; j++) {
			if (jbm->Get(i, j)) no++;
		}
	}

	printf("# Ones: %d\n", CRS_N_Ones(n, w));
	printf("\n");
	printf("Bitmatrix has %d ones\n", no);
	printf("\n");
	jbm->Print(w);

	return 0;
}
